﻿using BarrageGameAssistant.Core.Configs;
using BarrageGameAssistant.Core.Enums;
using BarrageGameAssistant.Core.Model;
using BarrageGameAssistant.Core.Utils;
using ImageProcess;
using M56.Core.Utils;
using System.Drawing.Imaging;
using BarrageGameAssistant.Core.Extensions;

namespace BarrageGameAssistant.UIForms
{
    public partial class FrmProcessMatchData : Form
    {
        private bool _newFlag = true; //新建标记
        private string sceneDir = string.Empty;
        private string matchImageFile = string.Empty;

        #region 基本属性
        public ProcessMatchData? MatchData;

        /// <summary>
        /// 
        /// </summary>
        public List<ProcessMatchData>? ProcessMatchDatas { get; set; }

        /// <summary>
        /// 程序配置
        /// </summary>
        public Settings? Settings { get; set; }

        /// <summary>
        /// 游戏配置
        /// </summary>
        public GameProject? CurrentGame { get; set; }

        /// <summary>
        /// 场景信息
        /// </summary>
        public Scene? Scene { get; set; }
        #endregion

        public Rectangle Box;

        private string _sceneImageFile = string.Empty;

        public FrmProcessMatchData()
        {
            InitializeComponent();
        }

        private System.Drawing.Image GetImage(string path)
        {
            using FileStream fs = new(path, FileMode.Open, FileAccess.Read);
            System.Drawing.Image result = System.Drawing.Image.FromStream(fs);
            fs.Close();
            return result;
        }

        private void FrmProcessMatchData_Load(object sender, EventArgs e)
        {
            if (Settings == null) return;
            if (CurrentGame == null) return;
            if(Scene == null) return;

            this.cbbPreProcessingMode.SelectedIndex = 0;
            this.cbbMatchType.SelectedIndex = 0;

            sceneDir = Scene.CurrentDirectory(CurrentGame);

            if (ProcessMatchDatas != null)
            {
                var jsonStr = JsonUtils.ToJson(ProcessMatchDatas, JsonUtils.DefaultSetting());
                var data0 = JsonUtils.FromJson<List<ProcessMatchData>>(jsonStr);
                var data1 = JsonUtils.FromJson<List<ProcessMatchData>>(jsonStr);

                this.cbbProgressBarKeyImage.DataSource = data0;
                this.cbbProgressBarKeyImage.DisplayMember = "Name";
                this.cbbProgressBarKeyImage.ValueMember = "Id";

                this.cbbProgressBarKeyImage1.DataSource = data1;
                this.cbbProgressBarKeyImage1.DisplayMember = "Name";
                this.cbbProgressBarKeyImage1.ValueMember = "Id";
            }

            if (MatchData == null)
            {
                _newFlag = true;
                MatchData = new ProcessMatchData((ProcessMatchType)cbbMatchType.SelectedIndex, Box);
                matchImageFile = Path.Combine(sceneDir, $"{MatchData.Id}.png");
                this.Text = "新建过程匹配项";

                _sceneImageFile = Path.Combine(sceneDir, $"{Scene?.Id}.png");
                using var matchImg = ImageProcess.ImageHelper.Crop(_sceneImageFile, MatchData.Bounds);
                matchImg?.Save(matchImageFile, ImageFormat.Png);
                this.pictureBox1.Image = GetImage(matchImageFile);
            }
            else
            {
                _newFlag = false;
                matchImageFile = Path.Combine(sceneDir, $"{MatchData.Id}.png");
                this.Text = "编辑过程匹配项";
                this.cbbPreProcessingMode.SelectedIndex = (int)MatchData.PreProcessingMode;

                this.cbbMatchType.SelectedIndex = (int)MatchData.MatchType;
                this.nudThreshold.Value = Convert.ToDecimal(MatchData.Threshold);
                if (MatchData.MatchType == ProcessMatchType.None)
                {
                    this.lbVariableName.Text = "图形标定名称：";
                    this.txtVariableName.Text = MatchData.Name;
                }
                else
                {
                    this.lbVariableName.Text = "对应变量名称：";
                    this.txtVariableName.Text = MatchData.VariableName;
                }
                this.nudProgressBarLeftValue.Value = Convert.ToDecimal(MatchData.ProgressBarLeftValue);
                this.nudProgressBarRightValue.Value = Convert.ToDecimal(MatchData.ProgressBarRightValue);
                this.cbbProgressBarKeyImage.Text = MatchData.ProgressBarKeyImage;
                this.cbbProgressBarKeyImage1.Text = MatchData.ProgressBarKeyImage1;
            }
        }

        

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (ProcessMatchDatas == null) return;

            if (string.IsNullOrEmpty(this.txtVariableName.Text))
            {
                if (cbbMatchType.SelectedIndex == 0)
                    MessageBox.Show(this, $"图形标定名称不能为空.", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show(this, $"对应变量名称不能为空.", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.txtVariableName.Focus();
                return;
            }

            if (cbbMatchType.SelectedIndex == 4 || cbbMatchType.SelectedIndex == 5)
            {
                if (string.IsNullOrEmpty(cbbProgressBarKeyImage.Text))
                {
                    MessageBox.Show(this, $"进度条标定图不能为空.", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.txtVariableName.Focus();
                    return;
                }
            }

            if (MatchData == null)
            {
                if (cbbMatchType.SelectedIndex == 0)
                {
                    if (ProcessMatchDatas.Any(x => x.Name == txtVariableName.Text))
                    {
                        MessageBox.Show(this, $"图形标定名称不能重复.", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.txtVariableName.Focus();
                        return;
                    }
                }
                else
                {
                    if (ProcessMatchDatas.Any(x => x.VariableName == txtVariableName.Text))
                    {
                        MessageBox.Show(this, $"变量名称不能重复.", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.txtVariableName.Focus();
                        return;
                    }
                }


                MatchData = new ProcessMatchData((ProcessMatchType)cbbMatchType.SelectedIndex, Box);

                if (cbbMatchType.SelectedIndex == 0) //图形标定
                {
                    MatchData.Name = this.txtVariableName.Text;
                    MatchData.VariableName = string.Empty;
                    this.nudProgressBarLeftValue.Value = -100;
                    this.cbbProgressBarKeyImage.SelectedValue = 100;
                }
                else
                {
                    MatchData.Name = string.Empty;
                    MatchData.VariableName = this.txtVariableName.Text;
                }

                MatchData.Threshold = Convert.ToDouble(this.nudThreshold.Value);
                MatchData.ProgressBarLeftValue = Convert.ToSingle(this.nudProgressBarLeftValue.Value);
                MatchData.ProgressBarRightValue = Convert.ToSingle(this.nudProgressBarRightValue.Value);

                if (cbbMatchType.SelectedIndex == 4 || cbbMatchType.SelectedIndex == 5)
                    MatchData.ProgressBarKeyImage = Convert.ToString(this.cbbProgressBarKeyImage.SelectedValue);
                else
                    MatchData.ProgressBarKeyImage = string.Empty;

                if (!string.IsNullOrEmpty(cbbProgressBarKeyImage.Text))
                    MatchData.ProgressBarKeyImage1 = Convert.ToString(this.cbbProgressBarKeyImage1.SelectedValue);

            }
            else
            {
                if (cbbMatchType.SelectedIndex == 0)
                {
                    if (ProcessMatchDatas.Any(x => x.Name == this.txtVariableName.Text && x.Id != MatchData.Id))
                    {
                        MessageBox.Show(this, $"图形标定名称不能重复.", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.txtVariableName.Focus();
                        return;
                    }
                }
                else
                {
                    if (ProcessMatchDatas.Any(x => x.VariableName == this.txtVariableName.Text && x.Id != MatchData.Id))
                    {
                        MessageBox.Show(this, $"变量名称不能重复.", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.txtVariableName.Focus();
                        return;
                    }
                }

                if (cbbMatchType.SelectedIndex == 0) //图形标定
                {
                    MatchData.Name = this.txtVariableName.Text;
                    MatchData.VariableName = string.Empty;
                    this.nudProgressBarLeftValue.Value = -100;
                    this.cbbProgressBarKeyImage.SelectedValue = 100;
                }
                else
                {
                    MatchData.Name = string.Empty;
                    MatchData.VariableName = this.txtVariableName.Text;
                }

                MatchData.Threshold = Convert.ToDouble(this.nudThreshold.Value);
                MatchData.ProgressBarLeftValue = Convert.ToSingle(this.nudProgressBarLeftValue.Value);
                MatchData.ProgressBarRightValue = Convert.ToSingle(this.nudProgressBarRightValue.Value);

                if (cbbMatchType.SelectedIndex == 4 || cbbMatchType.SelectedIndex == 5)
                    MatchData.ProgressBarKeyImage = Convert.ToString(this.cbbProgressBarKeyImage.SelectedValue);
                else
                    MatchData.ProgressBarKeyImage = string.Empty;

                if (!string.IsNullOrEmpty(cbbProgressBarKeyImage.Text))
                    MatchData.ProgressBarKeyImage1 = Convert.ToString(this.cbbProgressBarKeyImage1.SelectedValue);
            }

            this.DialogResult = DialogResult.OK;
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            //if (cbbMatchType.SelectedIndex > 0 && cbbMatchType.SelectedIndex < 4)
            //{
            //    string tmpFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Temp", $"{Guid.NewGuid()}.png");
            //    try
            //    {
            //        using var tmpImg = ImageHelper.Crop(SceneImage, MatchData == null ? this.Box : MatchData.Bounds);
            //        tmpImg?.Save(tmpFile);

            //        using OcrHelper ocr = new();
            //        ocr.Threshold = Convert.ToSingle(this.nudThreshold.Value);

            //        string result = ocr.GetText(tmpFile);

            //        if (!string.IsNullOrEmpty(result))
            //        {
            //            if (cbbMatchType.SelectedIndex == 1)
            //                MessageBox.Show(this, RegexUtils.GetDigit(result), "识别结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //            else if (cbbMatchType.SelectedIndex == 2)
            //                MessageBox.Show(this, RegexUtils.GetChinese(result), "识别结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //            else if (cbbMatchType.SelectedIndex == 3)
            //                MessageBox.Show(this, RegexUtils.GetEnglish(result), "识别结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //        }
            //    }
            //    catch (Exception)
            //    {
            //        MessageBox.Show(this, $"识别错误.", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    }
            //    finally
            //    {
            //        if (File.Exists(tmpFile))
            //        { File.Delete(tmpFile); }
            //    }
            //}
        }

        #region 下拉控件选择处理事件
        private void cbbPreProcessingMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (MatchData == null) return;

            if (Settings == null) return;
            if (CurrentGame == null) return;
            if (Scene == null) return;
            switch (this.cbbPreProcessingMode.SelectedIndex)
            {
                case 1:
                    _sceneImageFile = Path.Combine(sceneDir, $"{Scene?.Id}_hsv.png");
                    break;
                case 2:
                    _sceneImageFile = Path.Combine(sceneDir, $"{Scene?.Id}_gray.png");
                    break;
                case 3:
                    _sceneImageFile = Path.Combine(sceneDir, $"{Scene?.Id}_binary.png");
                    break;
                default:
                    _sceneImageFile = Path.Combine(sceneDir, $"{Scene?.Id}.png");
                    break;
            }
            if (File.Exists(_sceneImageFile))
            {
                using var matchImg = ImageProcess.ImageHelper.Crop(_sceneImageFile, MatchData.Bounds);
                matchImg?.Save(matchImageFile, ImageFormat.Png);
                this.pictureBox1.Image = GetImage(matchImageFile);
            }
        }

        private void cbbMatchType_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cbbMatchType.SelectedIndex)
            {
                case 1:
                    {
                        //数字识别
                        this.lbVariableName.Text = "对应变量名称：";
                        this.btnTest.Enabled = true;
                        this.nudProgressBarLeftValue.Enabled = false;
                        this.nudProgressBarRightValue.Enabled = false;
                        this.cbbProgressBarKeyImage.Enabled = false;
                        break;
                    }
                case 2:
                    {
                        //中文识别
                        this.lbVariableName.Text = "对应变量名称：";
                        this.btnTest.Enabled = true;
                        this.nudProgressBarLeftValue.Enabled = false;
                        this.nudProgressBarRightValue.Enabled = false;
                        this.cbbProgressBarKeyImage.Enabled = false;
                        break;
                    }
                case 3:
                    {
                        //英文识别
                        this.lbVariableName.Text = "对应变量名称：";
                        this.btnTest.Enabled = true;
                        this.nudProgressBarLeftValue.Enabled = false;
                        this.nudProgressBarRightValue.Enabled = false;
                        this.cbbProgressBarKeyImage.Enabled = false;
                        break;
                    }
                case 4:
                    {
                        //横进度条识别
                        this.lbVariableName.Text = "对应变量名称：";
                        this.btnTest.Enabled = true;
                        this.nudProgressBarLeftValue.Enabled = true;
                        this.nudProgressBarRightValue.Enabled = true;
                        this.cbbProgressBarKeyImage.Enabled = true;
                        break;
                    }
                case 5:
                    {
                        //竖进度条识别
                        this.lbVariableName.Text = "对应变量名称：";
                        this.btnTest.Enabled = true;
                        this.nudProgressBarLeftValue.Enabled = true;
                        this.nudProgressBarRightValue.Enabled = true;
                        this.cbbProgressBarKeyImage.Enabled = true;
                        break;
                    }
                case 6:
                    {
                        //位置追踪
                        this.lbVariableName.Text = "对应变量名称：";
                        this.btnTest.Enabled = true;
                        this.nudProgressBarLeftValue.Enabled = false;
                        this.nudProgressBarRightValue.Enabled = false;
                        this.cbbProgressBarKeyImage.Enabled = false;
                        break;
                    }
                default:
                    {
                        this.lbVariableName.Text = "图形标定名称：";
                        this.btnTest.Enabled = false;
                        this.nudProgressBarLeftValue.Enabled = false;
                        this.nudProgressBarRightValue.Enabled = false;
                        this.cbbProgressBarKeyImage.Enabled = false;
                        break;
                    }
            }
        }
        #endregion
    }
}
